package com.example.sxmall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sxmall.common.dto.PassDto;
import com.example.sxmall.common.lang.Result;
import com.example.sxmall.dao.mapper.OrdersMapper;
import com.example.sxmall.dao.pojo.Orders;
import com.example.sxmall.dao.pojo.Users;
import com.example.sxmall.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhang
 * @since 2022-03-25
 */
@RestController
@RequestMapping("/users")
public class UsersController extends BaseController {
    @Autowired
    BCryptPasswordEncoder passwordEncoder;
    @Autowired
    UsersService usersService;

    @Autowired(required = false)
    OrdersMapper ordersMapper;

    /*订单列表*/
    @GetMapping("/list")
    public Result list(Principal principal){
        Integer ouid = usersService.getUserIdByAct(principal.getName());
        List<Orders> ordersList = ordersMapper.selectList(new QueryWrapper<Orders>().eq("ouid",ouid));

        return Result.succ(ordersList);
    }
    /*注册*/
    @PostMapping("/register")
    public Result save(@Validated Users users) {
        users.setUregtime(LocalDateTime.now());//获取注册时间
        Users user = usersService.getByUsersName(users.getUaccount());

        if (user != null){
            return Result.fail("账户已经存在，请重新填写");
        }
        usersService.save(users);//保存
        return Result.succ(users);
    }

    /*修改个人信息*/
    @PostMapping("/update")
    public Result update(@Validated @RequestBody Users users,PassDto passDto) {
        users.setUpwd(passwordEncoder.encode(passDto.getPassword()));

        usersService.updateById(users);
        return Result.succ(users);
    }

}
